/**
 * simple cts upload example, written by wohlgemuth@ucdavis.edu - Gert Wohlgemuth
 */

/**
 * where can we find our dependencies
 */

@GrabResolver(name = 'binbase', root = 'http://binbase-maven.googlecode.com/svn/trunk/repo')
@GrabResolver(name = 'jboss', root = 'http://repository.jboss.com/maven2')
@GrabResolver(name = 'javanet', root = 'http://download.java.net/maven/2')
@GrabResolver(name = 'codehaus', root = 'http://repository.codehaus.org')
@GrabResolver(name = 'codehaus-snapshot', root = 'http://snapshots.repository.codehaus.org')

/**
 * we don't need these
 */
@GrabExclude('javax.jms:jms')
@GrabExclude('javax.transaction:jta')
@GrabExclude('org.springframework:spring:2.5')

/**
 * required dependencies, it can take a while to download them so be patiant
 */
@Grab(group = 'org.codehaus.groovy.modules', module = 'groovyws', version = '0.5.2')
@Grab(group = 'edu.ucdavis.genomics.metabolomics.binbase.connector', module = 'binbase-connector', version = '3.4.8')
@Grab(group = 'wsdl4j', module = 'wsdl4j', version = '1.6.2')

/**
 * required imports
 */
import groovyx.net.ws.WSClient
import org.openscience.cdk.interfaces.IChemObject
import org.openscience.cdk.io.iterator.IteratingMDLReader
import org.openscience.cdk.io.MDLWriter
import org.openscience.cdk.DefaultChemObjectBuilder
import org.openscience.cdk.Molecule

/**
 * check to command line arguments
 */
if (args.length != 2) {
    println "Usage:"
    println "args[0] = server:port"
    println "args[1] = fileName.sdf"
    println ""
    println "please provide the required arguments..."
    println ""
    return
}

/**
 * command line arguments
 */
def file = args[1]
def server = args[0]

/**
 * access the webserver
 */
proxy = new WSClient("http://${server}/cts/services/upload?wsdl", this.class.classLoader)
proxy.initialize()

IteratingMDLReader reader = new IteratingMDLReader(new FileInputStream(file),
        DefaultChemObjectBuilder.getInstance());

int count = 0;

/**
 * go over every molecule
 */
while (reader.hasNext()) {
    try {

        IChemObject mol = reader.next();

        if (mol != null) {
            ByteArrayOutputStream out = new ByteArrayOutputStream()
            MDLWriter writer = new MDLWriter(out);
            writer.writeMolecule((Molecule) mol);

            writer.close();

            String result = new String(out.toByteArray())


            long compoundId = proxy.uploadMolFile(result)

            println "generated new compound with id: ${compoundId}"

            count++
        }
        else {
            println "ignored molecule..."
        }
    } catch (NullPointerException e) {
    }
}

println "uploaded ${count} compounds"